<template>
  <div class="layout-pd">
    <div class="tabs">
      <div class="itm-nav" :class="[state.navActive == item.value ? 'active-nav' : '']"
        v-for="(item, index) in state.navArr" :key="index" @click="navClick(item.value)">
        {{ item.label }}
      </div>
    </div>
    <div class="container">
      <div class="search-btns">
        <div class="btns">
          <el-button v-if="auth(state.isHasAdd)" size="default" color="#18bc9c" @click="addFn">+ 添加</el-button>
        </div>
        <div class="search-name">
          <div class="block">
            <el-date-picker v-model="state.formData.dateRange" type="datetimerange" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleDateChange" />
          </div>
          <div class="search">
            <el-input v-model="state.formData.order_number" placeholder="请根据订单号查询" clearable
              class="input-with-select" />
          </div>
          <div class="search">
            <el-input v-model="state.formData.user_name" placeholder="请根据客户名称查询" clearable class="input-with-select" />
          </div>
          <div class="search">
            <el-input v-model="state.formData.follower_name" placeholder="可根据客户经理名称筛选" clearable
              class="input-with-select" />
          </div>
          <div class="search">
            <el-select v-model="state.quotation_situation" clearable placeholder="请选择">
              <el-option v-for="item in state.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="searchBth">
            <el-button type="primary" size="large" @click="searchFn" class="searchBtn1">查询</el-button>
          </div>

        </div>
      </div>
      <div class="tables">
        <YxTable :header-cell-style="{ background: '#f5f7fa' }" border :selection="false" :isSerialNum="false"
          :data="state.tableData" :columnData="state.columnData" :isPage="true" :total="state.total"
          :page="state.pages.page" :psize="state.pages.limit" @size-change="sizeChange" @current-change="currentChange"
          :showOperator="true">
          <template v-slot:show="{ row }">
            <span>{{ showInfo(row.show, showArr) }}</span>
          </template>
          <template v-slot:rating="{ row }">
            <span>{{ ratingMap[row.rating] }}</span>
          </template>
          <template v-slot:status="{ row }">
            <span>{{ clueStatus[row.status] }}</span>
          </template>
          <template v-slot:quotation_situation="{ row }">
            <span>{{ quotation[row.quotation_situation] }}</span>
          </template>
          <template v-slot:operate="{ row }">
            <el-button v-if="auth(state.isHasDistribute)" type="primary" text size="small" @click="openModal(row)"><i
                class="el-icon-user-plus"></i>分配人员</el-button>
            <!-- <el-button v-if="auth(state.isHasEdit)" type="primary" text size="small"
              @click="editRow(row)">编辑</el-button> -->
            <el-button v-if="auth(state.isHasFollow)" type="primary" text size="small"
              @click="followUp(row)">跟进</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="operateFn('del', row)">
              <template #reference>
                <el-button v-if="auth(state.isHasDel)" type="primary" text size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </YxTable>
      </div>
    </div>
    <AddClue ref="addClueRef" @updateList="getData"></AddClue>
    <!-- 分配人员弹框 -->
    <el-dialog v-model="dialogVisible" title="分配人员" :width="dialogWidth" :max-height="dialogMaxHeight"
      :before-close="handleClose" class="personnel-dialog">
      <!-- 搜索和选择区域 -->
      <div class="selection-container">
        <el-select v-model="selectedOptionalId" placeholder="请选择人员" filterable clearable remote
          :remote-method="handleRemoteSearch" :loading="loading" class="w-full mb-6" @change="handlePersonSelect">
          <template #default-value="scope">
            <template v-if="scope.value">
              <div v-if="selectedPerson" class="selected-display">
                <span class="name">{{ selectedPerson.username }}</span>
              </div>
            </template>
          </template>
          <!-- :disabled="isSelected(person.id)" -->
          <el-option v-for="person in filteredOptionalPersons" :key="person.id" :label="`${person.username}`"
            :value="person.id" />
        </el-select>
      </div>

      <!-- 底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer flex justify-between items-center w-full"
          style="display: flex;justify-content: space-between;">
          <div class="left-buttons flex gap-2">
          </div>
          <div class="right-button">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAllocation" :disabled="!selectedRight.length">
              <i class="el-icon-check mr-1"></i>确认分配
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="clueManageIndex">
import { PostSalesLeads, PostSalesLeadsGetUserList, PostSalesLeadsAllocation, PostSalesLeadsDel } from '/@/api/project/index';
import { navArr } from '/@/commmon/variate';
import { clueManageColumn } from '/@/commmon/column';
import { auth } from '/@/utils/authFunction';
import { defineAsyncComponent, reactive, ref, onMounted, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
const YxTable = defineAsyncComponent(() => import('/@/components/YxTable/index.vue'));
const AddClue = defineAsyncComponent(() => import('/@/views/startfab/clueManage/addClue.vue'));
const addClueRef = ref();
const state = reactive({
  isHasAdd: 'admin:admin:clueAdd',
  isHasEdit: 'admin:admin:clueEdit',
  isHasDel: 'admin:admin:clueDel',
  isHasDistribute: 'admin:admin:clueDistribute',
  isHasFollow: 'admin:admin:clueFollow',
  navArr: navArr,
  navActive: '',
  sortType: '',
  fieldType: '',
  sortTypeObj: {
    asc: 'asc',
    desc: 'desc',
  },
  formData: {
    keyword: '',
    dateRange: [],
  },
  columnData: clueManageColumn,
  total: 0,
  pages: {
    page: 1,
    limit: 10,
  },
  tableData: [],
  quotation_situation: '',
  options: [
    { value: '1', label: '已报价' },
    { value: '2', label: '未报价' },
  ],
});

// 弹框状态
const dialogVisible = ref(false);
const dialogWidth = ref('90%');
const dialogMaxHeight = ref('90vh');
const searchQuery = ref('');
const loading = ref(false);
const allPersons = ref([]);
const optionalPersons = ref([]);
const selectedRight = ref([]);
const selectedOptionalId = ref(null);
const selectedPerson = ref(null);
const listId = ref(null);
const ratingMap = ref({ 1: 'S级', 2: 'A级', 3: 'B级', 4: 'C级', 5: 'D级' });
const clueStatus = ref({ 'new': '新线索', 'public': '公海线索', 'contacted': '已联系', 'qualified': '已确认需求', 'converted': '已转化', 'assigned': '已分配', 'tofollowup': '待跟进', 'followedup': '已跟进' });
const quotation = ref({ '1': '已报价', '2': '未报价' });
const userList = async () => {
  const res = await PostSalesLeadsGetUserList();
  if (res.code === 10000) {
    allPersons.value = res.data;
    optionalPersons.value = [...allPersons.value]
  } else {
    ElMessage.error(res.msg);
  }
}

// 筛选后的可选人员
const filteredOptionalPersons = computed(() => {
  return optionalPersons.value.filter(person => {
    // 搜索筛选
    const searchMatch = !searchQuery.value
      || person.username.toLowerCase().includes(searchQuery.value.toLowerCase());
    return searchMatch;
  });
});

// 监听已选人员变化，更新回显信息
watch(selectedRight, (newVal) => {
  if (newVal.length > 0) {
    selectedPerson.value = newVal[0];
    selectedOptionalId.value = newVal[0].id;
  } else {
    selectedPerson.value = null;
    selectedOptionalId.value = null;
  }
}, { immediate: true });

// 打开弹框
const openModal = (row) => {
  listId.value = row.id;
  dialogVisible.value = true;
  adjustDialogWidth();
  window.addEventListener('resize', adjustDialogWidth);
};

// 关闭弹框
const handleClose = () => {
  dialogVisible.value = false;
  window.removeEventListener('resize', adjustDialogWidth);
  resetSelection();
};

// 重置选择状态
const resetSelection = () => {
  selectedOptionalId.value = null;
  selectedPerson.value = null;
  searchQuery.value = '';
};

// 调整弹框宽度
const adjustDialogWidth = () => {
  if (window.innerWidth < 768) {
    dialogWidth.value = '90%';
  } else {
    dialogWidth.value = '600px';
  }
};

// 远程搜索处理
const handleRemoteSearch = (query) => {
  searchQuery.value = query;
  // 模拟加载状态
  if (query) {
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
    }, 300);
  } else {
    loading.value = false;
  }
};

// 处理人员选中（下拉选择）
const handlePersonSelect = (personId) => {
  if (!personId) {
    // 如果清空选择，也清空已选列表
    selectedRight.value = [];
    return;
  }

  // 找到当前选中的人员（从所有人员中找，而不仅是可选列表）
  const selectedPersonItem = allPersons.value.find(p => p.id === personId);
  if (selectedPersonItem) {
    // 直接更新已选列表，不修改可选列表
    selectedRight.value = [selectedPersonItem];
  }
};

// 确认分配
const confirmAllocation = async () => {
  if (selectedRight.value.length === 0) {
    ElMessage.warning('请选择一名人员进行分配');
    return;
  }

  const [allocatedPerson] = selectedRight.value;

  const res = await PostSalesLeadsAllocation({
    id: listId.value,
    userid: allocatedPerson.id,
  });

  if (res.code == 10000) {
    getData();
    dialogVisible.value = false;
    window.removeEventListener('resize', adjustDialogWidth);
    resetSelection();
    ElMessage.success(`成功分配人员: ${allocatedPerson.username}`); // 移到这里
  } else {
    ElMessage.error(res.msg || '分配失败，请重试'); // 保留失败提示
  }
};
const navClick = (val) => {
  state.pages.page = 1;
  state.pages.limit = 10;
  state.navActive = val;
  setTimeout(() => {
    getData();
  }, 0);
};

const addFn = () => {
  addClueRef.value.openDialog('add');
};

const editRow = (row) => {
  addClueRef.value.openDialog('edit', row)
}

const operateFn = async (del, row) => {
  const params = {
    id: row.id,
  }

  const res = await PostSalesLeadsDel(params);
  if (res.code == 10000) {
    ElMessage.success(res.msg);
    getData();
  }
}

// 处理日期选择变化
const handleDateChange = (dateRange) => {
  if (dateRange && dateRange[0] && dateRange[1]) {
    if (new Date(dateRange[0]) > new Date(dateRange[1])) {
      ElMessage.error('开始时间不能晚于结束时间');
      state.formData.dateRange = [];
      return;
    }
    getData();
  } else {
    ElMessage.error('请选择完整的时间范围');
  }
};
const router = useRouter();
const followUp = (row) => {
  router.push({ path: '/followDetail', query: { id: row.id } })
}

const getData = async () => {
  const { dateRange } = state.formData;
  const [startTime = '', endTime = ''] = dateRange || [];
  const res = await PostSalesLeads({
    ...state.pages,
    startTime, // 开始时间字段
    endTime, // 结束时间字段
    status: state.navActive,
    username: state.formData.follower_name,
    order_number: state.formData.order_number,
    user_name: state.formData.user_name,
    quotation_situation: state.quotation_situation,
  });
  if (res.code == 10000) {
    state.tableData = res.data.list;
    state.total = res.data.pageInfo.count;
  }
};

const currentChange = (val) => {
  state.pages.page = val;
  getData();
};

const sizeChange = (val) => {
  state.pages.limit = val;
  getData();
};

const SEARCH_STORAGE_KEY = 'sales-leads-search-condition';

const searchFn = () => {
  state.pages.page = 1;
  state.pages.limit = 10;
  // 保存当前搜索条件到本地
  const saveData = {
    order_number: state.formData.order_number,
    user_name: state.formData.user_name,
    follower_name: state.formData.follower_name,
    dateRange: state.formData.dateRange,
    page: state.pages.page,
    navActive: state.navActive,
    quotation_situation: state.quotation_situation,
  };
  localStorage.setItem(SEARCH_STORAGE_KEY, JSON.stringify(saveData));
  getData();
};

onMounted(() => {
  const saved = localStorage.getItem(SEARCH_STORAGE_KEY);
  if (saved) {
    try {
      const data = JSON.parse(saved);
      // 恢复搜索条件
      state.formData.order_number = data.order_number || '';
      state.formData.user_name = data.user_name || '';
      state.formData.follower_name = data.follower_name || '';
      state.formData.dateRange = data.dateRange || [];
      state.pages.page = data.page || 1;
      state.navActive = data.navActive || '';
      state.quotation_situation = data.quotation_situation || '';
    } catch (e) {
      console.warn('解析本地搜索状态失败', e);
    }
  }
  userList();
  searchFn();
  optionalPersons.value = optionalPersons.value.filter(p =>
    !selectedRight.value.some(sp => sp.id === p.id)
  );
});
</script>

<style scoped lang="scss">
.tabs {
  padding: 15px 15px 0px 15px;
  background: #e8edf0;
  border-color: #e8edf0;
  position: relative;
  display: flex;

  .itm-nav {
    background: #d8e0e6;
    padding: 10px 15px;
    margin-right: 4px;
    cursor: pointer;
  }

  .active-nav {
    background: #ffffff;
  }
}

.container {
  background: #ffffff;
  padding: 15px;

  ::v-deep .search-btns {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .search-name {
      display: flex;

      .search {
        margin-right: 10px;
      }

      .searchBth {
        width: 100px;
        margin-right: 10px;

        .searchBtn1 {
          width: 100px;
        }
      }

      .block {
        margin-right: 10px;
      }
    }

    .el-input-group__append {
      padding: 0px 15px;

      .el-icon {
        color: #333333;
        margin-right: 0px;
      }
    }

    .el-button {
      color: #ffffff;
    }
  }

  .tables {
    margin-top: 10px;
  }

  :deep(.personnel-allocation) {
    .personnel-dialog {
      --el-dialog-body-padding: 20px;
    }

    .selection-container {
      width: 100%;
    }

    .selected-section {
      border: 1px solid var(--el-border-color);
      border-radius: var(--el-border-radius-base);
      overflow: hidden;
    }

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid var(--el-border-color);
      background-color: var(--el-bg-color);

      .list-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .count-badge {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        background-color: var(--el-fill-color);
        padding: 2px 8px;
        border-radius: 12px;

        &.selected-count {
          color: var(--el-color-primary);
          background-color: var(--el-color-primary-light-9);
        }
      }
    }

    .selected-items {
      padding: 16px;
      min-height: 120px;

      .personnel-item {
        padding: 10px 12px;
        border-radius: var(--el-border-radius-base);
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &.selected-item {
          background-color: var(--el-color-primary-light-9);

          &:hover {
            background-color: var(--el-color-primary-light-8);
          }
        }

        .person-info {
          display: flex;
          align-items: center;
          flex: 1;

          .person-details {
            flex: 1;
            min-width: 0;

            .person-name {
              font-size: 14px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 2px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .person-department {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }

        .delete-btn {
          color: var(--el-color-danger);
          margin-left: 8px;
          opacity: 0.7;

          &:hover {
            opacity: 1;
            color: var(--el-color-danger);
          }
        }
      }

      .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
      }
    }

    .dialog-footer {
      padding: 12px 16px 16px;
      border-top: 1px solid var(--el-border-color);
      margin-top: 8px;
    }
  }
}
</style>
